<template>
  <div class="fba-print-label-wrap">
    <div class="print-w">
      <div class="print-setting">
        <ChoosePrintList ref="choosePrintRef" @getLodop="getLodop" />
        <!-- <div class="printer-w">
          <a-button type="text" @click="openUrl">
            <span>打印说明</span>
            <icon-question-circle />
          </a-button>
          <p class="title">打印机：</p>
          <select id="Select02" @change="createBridgeSubPrinterSelectList"></select>
          <a-select size="small" style="width: 300px" v-model="selectPrinter" placeholder="选择打印机">
            <a-option v-for="(item, i) in printerList" :key="i" :value="item.value" :label="item.name" />
          </a-select>
          <div class="flex-c">
            <p>未检测到打印控件</p>
            <a-button type="text">点击下载（安装完成后请刷新页面）</a-button>
          </div>
        </div> -->
        <div class="flex-c" style="margin-bottom: 20px">
          <p class="title">选择打印模板：</p>
          <a-dropdown position="bl" trigger="hover">
            <a-button class="gray-outline flex-c-sb" style="min-width: 160px"> {{ currentTemp.templateName || '默认模板' }} <icon-down /> </a-button>
            <template #content>
              <a-doption @click="resetTemp">默认模板</a-doption>
              <a-doption v-for="(item, i) in tempList" :key="i" @click="changeTemplate(item)">{{ item.templateName }}</a-doption>
            </template>
          </a-dropdown>
        </div>
        <a-row style="margin-bottom: 40px">
          <a-col :span="6">
            <p class="title">
              <span>纸张宽度</span>
              <a-popover content="最大支持100mm * 100mm">
                <icon-question-circle />
              </a-popover>
            </p>
            <a-input-group>
              <div class="input-group">
                <a-input-number v-model="printConfig.pageSizeWidth" style="width: 70px" placeholder="" :min="0" :max="100" />
                <div class="unit">mm</div>
              </div>
            </a-input-group>
          </a-col>
          <a-col :span="8">
            <p class="title">
              <span>介质大小</span>
              <a-popover content="最大支持100mm * 100mm">
                <icon-question-circle />
              </a-popover>
            </p>
            <a-input-group>
              <div class="input-group">
                <a-input-number v-model="printConfig.mediumWidth" style="width: 70px" placeholder="" :min="0" :max="100" />
                <span class="label">宽</span>
              </div>
              <div class="input-group">
                <a-input-number v-model="printConfig.mediumHeight" style="width: 70px" placeholder="" :min="0" :max="100" />
                <div class="unit">mm</div>
                <span class="label">高</span>
              </div>
            </a-input-group>
          </a-col>
          <a-col :span="9">
            <p class="title">字体：</p>
            <div class="flex-c">
              <div class="input-group">
                <a-input-number v-model="printConfig.fontSize" style="width: 90px; margin-right: 10px" placeholder="" :min="10" :max="16" />
                <span class="label">大小</span>
              </div>
              <div class="input-group">
                <a-input-number v-model="printConfig.fontIndex" style="width: 90px" placeholder="" :min="0" :max="100" />
                <span class="label">字间距</span>
              </div>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-bottom: 40px">
          <a-col :span="12">
            <p class="title">
              <span>条码大小</span>
              <a-popover content="条码大小由编码生成，请确保条码大小介于介质大小之间">
                <icon-question-circle />
              </a-popover>
            </p>
            <a-input-group style="margin-right: 10px">
              <div class="input-group">
                <a-input-number v-model="printConfig.codeWidth" style="width: 70px" placeholder="" :min="0" :max="100" />
                <div class="unit">mm</div>
                <span class="label">宽</span>
              </div>
            </a-input-group>
            <a-input-group>
              <div class="input-group">
                <a-input-number v-model="printConfig.codeHeight" style="width: 70px" placeholder="" :min="0" :max="100" />
                <div class="unit">mm</div>
                <span class="label">高</span>
              </div>
            </a-input-group>
          </a-col>
          <a-col :span="12">
            <p class="title">
              <span>边距</span>
              <a-popover>
                <template #content>
                  <p style="width: 400px">亚马逊标签要求周围保留足够的空白,左右保留0.25英寸(约6.4mm),上下保留0.125英寸(约3.2mm)</p>
                </template>
                <icon-question-circle />
              </a-popover>
            </p>
            <a-input-group>
              <div class="input-group">
                <a-input-number v-model="printConfig.paddingTop" style="width: 60px" placeholder="" :min="0" :max="100" />
                <span class="label">上</span>
              </div>
              <div class="input-group">
                <a-input-number v-model="printConfig.paddingBottom" style="width: 60px" placeholder="" :min="0" :max="100" />
                <span class="label">下</span>
              </div>
              <div class="input-group">
                <a-input-number v-model="printConfig.paddingLeft" style="width: 60px" placeholder="" :min="0" :max="100" />
                <span class="label">左</span>
              </div>
              <div class="input-group">
                <a-input-number v-model="printConfig.paddingRight" style="width: 60px" placeholder="" :min="0" :max="100" />
                <span class="label">右</span>
              </div>
              <div class="unit">mm</div>
            </a-input-group>
          </a-col>
        </a-row>
        <a-row style="margin-bottom: 20px">
          <a-col :span="7">
            <p class="title">打印列表：</p>
            <a-radio-group v-model="printConfig.columnsNum">
              <a-radio :value="1">单排</a-radio>
              <a-radio :value="2">双排</a-radio>
            </a-radio-group>
          </a-col>
          <a-col :span="8">
            <p class="title">
              <span>不同产品标签自动区隔:</span>
              <a-popover>
                <template #content>
                  <p style="width: 400px">若选择“是”，则打印时会在不同FNSKU/SKU标签前自动插入一个空白标签加以区隔，适合用于单个产品标签打印数量较多时。 若选择“否”，则只会逐个打印，不会自动插入空白标签。</p>
                </template>
                <icon-question-circle />
              </a-popover>
            </p>
            <a-radio-group v-model="printConfig.isAuto">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </a-col>
          <a-col :span="9">
            <p class="title">
              <span>是否打印货件号:</span>
              <a-popover>
                <template #content>
                  <p style="width: 400px">若选择“是”，则打印时会在每个货件打印前插入一个货件标签（包含发货单号，货件号）。</p>
                </template>
                <icon-question-circle />
              </a-popover>
            </p>
            <div class="flex-c">
              <a-radio-group v-model="printConfig.isPrintFba">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
              <a-input-group v-if="printConfig.isPrintFba">
                <div class="input-group">
                  <a-input-number v-model="printConfig.printNum" style="width: 60px" placeholder="" :min="1" />
                  <div class="unit">份</div>
                </div>
              </a-input-group>
            </div>
          </a-col>
        </a-row>
        <div class="print-con" style="margin-bottom: 20px">
          <p class="title">打印内容设置：</p>
          <a-checkbox-group v-model="printConfig.fieldList">
            <a-checkbox style="width: 150px" v-for="(item, i) in Object.values(allFieldList)" :key="i" :value="item.key">{{ item.name }}</a-checkbox>
          </a-checkbox-group>
        </div>
      </div>
      <div class="barcode-win">
        <a class="link" href="https://sellercentral.amazon.com/gp/help/external/200111490?language=zh_CN" target="_blank">亚马逊商品标签要求</a>
        <div class="print-media-wapper">
          <div class="print-media" :style="`width: ${printConfig.mediumWidth}mm; height: ${printConfig.mediumHeight}mm;padding:${printConfig.paddingTop}mm ${printConfig.paddingRight}mm ${printConfig.paddingBottom}mm ${printConfig.paddingLeft}mm`">
            <div class="print-media-padding">
              <div
                class="print-item"
                @mousedown="moveItem($event, 0, 0, 'code')"
                :class="{ active: currentIndex === 0 }"
                :style="`
                  width: ${printConfig.codeWidth}mm; 
                  height: ${printConfig.codeHeight}mm;
                  left:${printConfig.elementPosition['code'] ? printConfig.elementPosition['code'].left : 0}px;
                  top:${printConfig.elementPosition['code'] ? printConfig.elementPosition['code'].top : 0}px`"
              >
                <img id="imgcode" :src="brcode" />
              </div>
              <div
                class="print-item"
                @mousedown="moveItem($event, 0, i + 1, key)"
                @click="currentIndex = i + 1"
                :class="{ active: currentIndex === i + 1 }"
                v-for="(key, i) in printConfig.fieldList"
                :key="i"
                :style="`
                  font-size:${printConfig.fontSize}pt;
                  left:${printConfig.elementPosition[key] ? printConfig.elementPosition[key].left : 0}px;
                  top:${printConfig.elementPosition[key] ? printConfig.elementPosition[key].top : 0}px`"
              >
                {{ allFieldList[key].defaultVal }}
              </div>
            </div>
          </div>
          <div class="print-media" v-if="printConfig.columnsNum == 2" :style="`width: ${printConfig.mediumWidth}mm; height: ${printConfig.mediumHeight}mm;padding:${printConfig.paddingTop}mm ${printConfig.paddingRight}mm ${printConfig.paddingBottom}mm ${printConfig.paddingLeft}mm;border-left:1px solid #eee`">
            <div class="print-media-padding">
              <div
                class="print-item"
                @mousedown="moveItem($event, 0, 0, 'code')"
                :class="{ active: currentIndex === 0 }"
                :style="`
                  width: ${printConfig.codeWidth}mm; 
                  height: ${printConfig.codeHeight}mm;
                  left:${printConfig.elementPosition['code'] ? printConfig.elementPosition['code'].left : 0}px;
                  top:${printConfig.elementPosition['code'] ? printConfig.elementPosition['code'].top : 0}px`"
              >
                <img id="imgcode" :src="brcode" />
              </div>
              <div
                class="print-item"
                @mousedown="moveItem($event, 0, i + 1, key)"
                @click="currentIndex = i + 1"
                :class="{ active: currentIndex === i + 1 }"
                v-for="(key, i) in printConfig.fieldList"
                :key="i"
                :style="`
                  font-size:${printConfig.fontSize}pt;
                  left:${printConfig.elementPosition[key] ? printConfig.elementPosition[key].left : 0}px;
                  top:${printConfig.elementPosition[key] ? printConfig.elementPosition[key].top : 0}px`"
              >
                {{ allFieldList[key].defaultVal }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="handle-w">
      <a-space>
        <!-- <a-button class="gray-outline" size="medium" @click="removeAll">全部移除</a-button> -->
        <a-button class="gray-outline" size="medium" @click="closePage">取消打印</a-button>
        <AddPrintTemp :currentTemp="currentTemp" templateCode="PRINT_FBA_LABEL" :content="printConfig" @success="getTemplateList" />
        <a-button type="primary" @click="toPrint(selectIds)" :disabled="!selectIds.length">打印</a-button>
        <p>
          <span>已选 </span>
          <span class="highlight"> {{ selectIds.length }} </span>
        </p>
      </a-space>
    </div>
    <div class="table-wrap">
      <a-table
        class="table-tow-line"
        ref="tableRef"
        row-key="id"
        :loading="tableLoading"
        @selection-change="selectColumn"
        :row-selection="rowSelection"
        :scroll="{
          y: '100%',
        }"
        :data="tableList"
        size="mini"
        :bordered="false"
        :pagination="false"
      >
        <template #columns>
          <a-table-column data-index="img" title="图片" :width="60">
            <template #cell="{ record }">
              <ImgPopover :src="record.productImg">
                <template #con>
                  <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                </template>
              </ImgPopover>
            </template>
          </a-table-column>
          <a-table-column title="单据号" :width="100" data-index="billNo" />
          <a-table-column title="货件号" :width="110" data-index="shipmentId" />
          <a-table-column title="MSKU/FNSKU" :width="120">
            <template #cell="{ record }">
              <TextLimit :rows="1">{{ record.msku || '--' }}</TextLimit>
              <TextLimit :rows="1">{{ record.fnsku || '--' }}</TextLimit>
            </template>
          </a-table-column>
          <a-table-column data-index="sku" title="SKU" :width="120" />
          <a-table-column data-index="productName" title="产品名称" :width="120">
            <template #cell="{ record }">
              <TextLimit>{{ record.productName }}</TextLimit>
            </template>
          </a-table-column>
          <a-table-column data-index="productNamePrint" title="产品名称（打印）" :width="140">
            <template #cell="{ record }">
              <a-textarea v-model="record.productNamePrint" />
            </template>
          </a-table-column>
          <a-table-column title="打印数量" :width="120">
            <template #cell="{ record, rowIndex }">
              <a-input-number v-model="record.printNum" style="width: 90px" placeholder="" :min="1" :max="record.unboxedNum" />
              <icon-double-down v-if="rowIndex === 0" class="edit-icon" @click="setGlobal(record, 'printNum')" />
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="60">
            <template #cell="{ record, rowIndex }">
              <a-space>
                <a-button type="text" @click="toPrint([record.id])">打印</a-button>
                <a-button type="text" @click="removeSingle(record, rowIndex)">移除</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive, computed } from 'vue'
  import brcode from '@/assets/brcode.png'
  import ChoosePrintList from '@/components/Print/choosePrintList.vue'
  import { findFbaShipmentPageByStore } from '@/api/purchase'
  import { findTemplateList } from '@/api/export'
  import { parseJson } from '@/utils'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import { useRouter, useRoute } from 'vue-router'

  onMounted(async () => {
    getFbaList()
    await getTemplateList()
    if (tempList.value.length) {
      changeTemplate(tempList.value[0])
    }
  })

  const visitedRouteStore = useVisitedRouteStore()
  const tableList = ref<Array<any>>([])
  const currentTemp = ref<any>({})
  const tempList = ref<Array<any>>([])
  const tableLoading = ref(false)
  const tableListMap = ref({})
  const selectRows = ref<any>([])
  const selectIds = ref([])
  const tableRef = ref()
  const route = useRoute()
  const router = useRouter()
  const originData = {
    mediumWidth: 50,
    mediumHeight: 25,
    codeHeight: 10,
    codeWidth: 40,
    fontSize: 10,
    fontIndex: 0,
    paddingTop: 2,
    paddingBottom: 2,
    paddingLeft: 2,
    paddingRight: 2,
    pageSizeWidth: 50,
    columnsNum: 1,
    isAuto: false,
    printNum: 2,
    isPrintFba: false,
    fieldList: ['fnsku', 'productNamePrint', 'new'],
    elementPosition: {
      code: { left: 0, top: 0 },
      fnsku: { left: 0, top: 40 },
      productNamePrint: { left: 0, top: 55 },
      new: { left: 0, top: 69 },
    },
  }
  const printConfig = ref<any>(JSON.parse(JSON.stringify(originData)))
  const currentIndex = ref()
  const choosePrintRef = ref()
  const currentBillNo = ref('')

  let LODOP: any = {}
  // 除去边距纸张区域，可用于设置文字大小
  const currentWidth = computed(() => Number(printConfig.value.mediumWidth || 0) - Number(printConfig.value.paddingLeft || 0) - Number(printConfig.value.paddingRight || 0))

  var isMoving = true

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const allFieldList = {
    fnsku: { name: 'FNSKU', key: 'fnsku', defaultVal: 'X003R61BTJ' },
    msku: { name: 'MSKU', key: 'msku', defaultVal: 'WMX10842-HKP' },
    productName: { name: '产品名称', key: 'productName', defaultVal: 'Horse Gifts for Women' },
    productNamePrint: { name: '产品名称(打印)', key: 'productNamePrint', defaultVal: 'Horse Gifts for Women' },
    sku: { name: 'SKU', key: 'sku', defaultVal: 'WME20815KP' },
    new: { name: 'New', key: 'new', defaultVal: 'New' },
    billNo: { name: '单据号', key: 'billNo', defaultVal: 'FBA172KTH2CP' },
  }

  function selectColumn(val: any) {
    selectIds.value = val
  }

  //获取导出模板
  async function getTemplateList() {
    const res: any = await findTemplateList({ templateType: 2, templateCode: 'PRINT_FBA_LABEL' })
    tempList.value = res?.data || []
  }
  //切换模板
  function changeTemplate(item: any) {
    currentTemp.value = item
    printConfig.value = parseJson(item.templateContent, [])
    setElementPosition()
  }
  function resetTemp() {
    currentTemp.value = {}
    printConfig.value = JSON.parse(JSON.stringify(originData))
    setElementPosition()
  }
  // 关闭界面
  function closePage() {
    visitedRouteStore.removeVisitedRoute(route)
    router.go(-1)
  }

  // 设置各元素初始位置
  function setElementPosition() {
    Object.keys(allFieldList).forEach((key: string) => {
      printConfig.value.elementPosition[key] = printConfig.value.elementPosition[key] || { ledt: 0, top: 0 }
    })
  }
  setElementPosition()

  // 移动位置
  function moveItem(e: any, parentIndex: number, index: number, key: string) {
    currentIndex.value = index
    isMoving = true
    let barcodeWrap: any = document.querySelector('.barcode-win')
    let fbaWrap: any = document.querySelector('.vaw-side-bar-wrapper')

    let currentParentNode: any = document.querySelectorAll('.print-media-padding')[parentIndex]
    currentParentNode

    let elDom: any = currentParentNode.querySelectorAll('.print-item')[index]

    var pageW = document.documentElement.clientWidth
    let pageH = document.documentElement.clientHeight
    var itemW = elDom.offsetWidth
    var itemH = elDom.offsetHeight

    var distanceX = fbaWrap.clientWidth + currentParentNode.offsetLeft + barcodeWrap.offsetLeft + e.offsetX
    var distanceY = 88 + currentParentNode.offsetTop + barcodeWrap.offsetTop + e.offsetY

    document.onmousemove = function (e) {
      var e = e || window.event
      // 移动的位置，鼠标的位置减去鼠标与元素左边和顶部的相对位置。
      var moveX = e.pageX - distanceX
      var moveY = e.pageY - distanceY

      //判断移动的位置是否超出页面，是的话就不能移动。
      // 移动的最大位置
      var maxX = pageW - itemW
      var maxY = pageH - itemH

      moveX = Math.min(maxX, Math.max(0, moveX))
      moveY = Math.min(maxY, Math.max(0, moveY))
      // 判断是否可移动
      if (isMoving === true) {
        printConfig.value.elementPosition[key].top = moveY
        printConfig.value.elementPosition[key].left = moveX
      }
      document.onmouseup = function () {
        isMoving = false
      }
    }
  }
  function getLodop(val: any) {
    LODOP = val
  }

  function getSelectRows(list: Array<any>) {
    selectRows.value = []
    list.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  //设置全局
  async function setGlobal(item: any, key: string) {
    tableList.value.forEach((el: any) => {
      el[key] = item[key]
    })
  }

  // 单个移除
  function removeSingle(row: any, index: number) {
    tableList.value.splice(index, 1)
    let _index: number = selectIds.value.findIndex((id: string) => id === row.id)
    if (_index > -1) {
      selectIds.value.splice(_index, 1)
    }
  }
  // 获取FBA详情
  async function getFbaList() {
    tableList.value = []
    tableListMap.value = {}
    let ids = window.sessionStorage.getItem('fbaPrintLabelId')
    tableLoading.value = true
    const res: any = await findFbaShipmentPageByStore({
      ids,
      pageSize: 1000,
      pageNum: 1,
    })
    tableLoading.value = false
    let fbaList = res?.data?.records || []
    fbaList.forEach((item: any) => {
      item.skuDetails?.forEach((el: any) => {
        let obj = {
          ...el,
          printNum: el.realNum,
          billNo: item.billNo,
          shipmentId: item.shipmentId,
          centerId: item.centerId,
          productNamePrint: el.productName,
          id: item.id + el.msku + el.sku,
          new: 'New',
        }
        tableList.value.push(obj)
        tableListMap.value[obj.id] = obj
      })
    })
  }
  // 设置html打印内容
  function toPrint(list: Array<any>) {
    let { type, bridgeIDandName, printerIndex } = choosePrintRef.value.getBridgeInfo()
    let pageSize = (printConfig.value.pageSizeWidth || printConfig.value.mediumWidth) + 'mm'
    LODOP.PRINT_INITA(printConfig.value.paddingTop + 'mm', printConfig.value.paddingLeft + 'mm', pageSize, printConfig.value.mediumHeight + 'mm', '打印标签')
    // 纸张大小
    LODOP.SET_PRINT_PAGESIZE(1, pageSize, printConfig.value.mediumHeight + 'mm', 'CreateCustomPage')
    //  指定打印机设备
    if (type === 1) {
      LODOP.SET_BRIDGE_INDEX(bridgeIDandName + ',' + printerIndex)
    } else {
      LODOP.SET_PRINTER_INDEX(printerIndex)
    }
    currentBillNo.value = ''
    // 打印内容
    createPage(list)
    // 打印预览
    LODOP.PREVIEW()
  }
  // 设置打印的字符
  function getPrintVal(val: string) {
    if (!val) return ''
    const canvas = document.createElement('canvas')
    const ctx: any = canvas.getContext('2d')
    ctx.font = `${printConfig.value.fontSize}pt Microsoft YaHei`
    const textWidth = ctx.measureText(val.toUpperCase()).width
    const size = currentWidth.value * 3.779
    const lengthLimit = parseInt((size / (textWidth / val.length)).toString()) || 20
    // 限制字符长度
    if (val.length <= lengthLimit) return val || ''
    const headVal = val.split(' ')?.[0]
    const footerVal = val.slice((lengthLimit - headVal.length - 3) * -1)
    return headVal + '...' + footerVal
  }
  function createPage(list: Array<any>) {
    LODOP.SET_PRINT_STYLE('FontName', 'Microsoft YaHei')
    LODOP.SET_PRINT_STYLEA('All', 'LetterSpacing', (printConfig.value.fontIndex || 0) + 'pt')
    getSelectRows(list)

    if (printConfig.value.columnsNum === 1) {
      // 单排打印
      sinleColumnData()
    } else if (printConfig.value.isAuto) {
      // 双排打印需要自动区隔
      twoColumnDataAndAuto()
    } else {
      // 双排打印
      twoColumnData()
    }
  }
  // 打印发货单
  function printFbaBill(item: any) {
    if (!printConfig.value.isPrintFba || currentBillNo.value === item.billNo) return
    for (let i = 0; i < printConfig.value.printNum; i++) {
      let left = 0
      if ((i + 1) % 2 === 0 && printConfig.value.columnsNum === 2) {
        left = '53mm'
      } else {
        left = 0
        LODOP.NEWPAGE()
      }
      LODOP.SET_PRINT_STYLE('Alignment', 2)
      LODOP.SET_PRINT_STYLE('FontSize', 12)
      LODOP.ADD_PRINT_TEXT('3mm', left, currentWidth.value + 'mm', 16, item.billNo || '--')
      LODOP.ADD_PRINT_TEXT('9mm', left, currentWidth.value + 'mm', 16, item.shipmentId || '--')
      LODOP.ADD_PRINT_TEXT('15mm', left, currentWidth.value + 'mm', 16, item.centerId || '--')
    }
    currentBillNo.value = item.billNo
  }
  // 单排打印
  function sinleColumnData() {
    selectRows.value.forEach((el: any) => {
      printFbaBill(el)
      if (printConfig.value.isAuto) {
        // 间隔标签
        LODOP.NEWPAGE()
        LODOP.SET_PRINT_STYLE('Alignment', 2)
        LODOP.SET_PRINT_STYLE('FontSize', 12)
        LODOP.ADD_PRINT_TEXT('3mm', 0, currentWidth.value + 'mm', 16, el.fnsku)
        LODOP.ADD_PRINT_TEXT('9mm', 0, currentWidth.value + 'mm', 16, el.sku)
        LODOP.ADD_PRINT_TEXT('15mm', 0, currentWidth.value + 'mm', 16, `(${el.printNum})`)
      }
      LODOP.SET_PRINT_STYLE('Alignment', 1)
      LODOP.SET_PRINT_STYLE('FontSize', printConfig.value.fontSize)
      for (let i = 0; i < el.printNum; i++) {
        LODOP.NEWPAGE()
        LODOP.ADD_PRINT_BARCODE(getTop('code'), getLeft('code'), printConfig.value.codeWidth + 'mm', printConfig.value.codeHeight + 'mm', '128B', el.fnsku)
        LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
        printConfig.value.fieldList.forEach((key: string) => {
          LODOP.ADD_PRINT_TEXT(getTop(key), getLeft(key), currentWidth.value + 'mm', printConfig.value.fontSize + 'pt', getPrintVal(el[key]))
        })
      }
    })
  }
  // 双排打印自动区隔
  function twoColumnDataAndAuto() {
    selectRows.value.forEach((el: any) => {
      printFbaBill(el)
      // 间隔标签
      LODOP.NEWPAGE()
      LODOP.SET_PRINT_STYLE('Alignment', 2)
      LODOP.SET_PRINT_STYLE('FontSize', 12)
      LODOP.ADD_PRINT_TEXT('3mm', 0, currentWidth.value + 'mm', 16, el.fnsku)
      LODOP.ADD_PRINT_TEXT('9mm', 0, currentWidth.value + 'mm', 16, el.sku)
      LODOP.ADD_PRINT_TEXT('15mm', 0, currentWidth.value + 'mm', 16, `(${el.printNum})`)

      LODOP.SET_PRINT_STYLE('Alignment', 1)
      LODOP.SET_PRINT_STYLE('FontSize', printConfig.value.fontSize)
      for (let i = 0; i < el.printNum; i++) {
        if ((i + 1) % 2 != 0) {
          // 偶数列
          LODOP.ADD_PRINT_BARCODE(getTop('code'), getLeft('code') + '53mm', printConfig.value.codeWidth + 'mm', printConfig.value.codeHeight + 'mm', '128B', el.fnsku)
          LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
          printConfig.value.fieldList.forEach((key: string) => {
            LODOP.ADD_PRINT_TEXT(getTop(key), getLeft(key) + 3.78 * 53, currentWidth.value + 'mm', printConfig.value.fontSize + 'pt', getPrintVal(el[key]))
          })
        } else {
          // 单数列
          LODOP.NEWPAGE()
          LODOP.ADD_PRINT_BARCODE(getTop('code'), getLeft('code'), printConfig.value.codeWidth + 'mm', printConfig.value.codeHeight + 'mm', '128B', el.fnsku)
          LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
          printConfig.value.fieldList.forEach((key: string) => {
            LODOP.ADD_PRINT_TEXT(getTop(key), getLeft(key), currentWidth.value + 'mm', printConfig.value.fontSize + 'pt', getPrintVal(el[key]))
          })
        }
      }
    })
  }

  // 双排打印不需要隔断
  function twoColumnData() {
    let list: Array<any> = []
    selectRows.value.forEach((el: any) => {
      for (let i = 0; i < el.printNum; i++) {
        list.push(el)
      }
    })
    list.forEach((el: any, i: number) => {
      printFbaBill(el)
      LODOP.SET_PRINT_STYLE('Alignment', 1)
      LODOP.SET_PRINT_STYLE('FontSize', printConfig.value.fontSize)
      if (i % 2 == 0) {
        // 单数列
        LODOP.NEWPAGE()
        LODOP.ADD_PRINT_BARCODE(getTop('code'), getLeft('code'), printConfig.value.codeWidth + 'mm', printConfig.value.codeHeight + 'mm', '128B', el.fnsku)
        LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
        printConfig.value.fieldList.forEach((key: string) => {
          LODOP.ADD_PRINT_TEXT(getTop(key), getLeft(key), currentWidth.value + 'mm', printConfig.value.fontSize + 'pt', getPrintVal(el[key]))
        })
      } else {
        // 偶数列
        LODOP.ADD_PRINT_BARCODE(getTop('code'), getLeft('code') + '53mm', printConfig.value.codeWidth + 'mm', printConfig.value.codeHeight + 'mm', '128B', el.fnsku)
        LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
        printConfig.value.fieldList.forEach((key: string) => {
          LODOP.ADD_PRINT_TEXT(getTop(key), getLeft(key) + 3.78 * 53, currentWidth.value + 'mm', printConfig.value.fontSize + 'pt', getPrintVal(el[key]))
        })
      }
    })
  }
  function getLeft(key: string) {
    return printConfig.value.elementPosition[key]?.left || 0
  }
  function getTop(key: string) {
    return printConfig.value.elementPosition[key]?.top || 0
  }
</script>
<style lang="less" scoped>
  .fba-print-label-wrap {
    min-height: calc(100vh - @menuHeight);
    background-color: #fff;
    padding: 10px 20px 10px;
    .table-wrap {
      overflow: hidden;
      margin: 10px 0;
      max-height: calc(100vh - @menuHeight);
    }
  }
  .print-w {
    display: flex;
    overflow: auto;

    .arco-input-group {
      border: 1px solid #dadde2;
      border-radius: 3px;
      .arco-input-wrapper {
        border: none;
        border-right: 1px solid #dadde2;
      }
    }
    .unit {
      background-color: #f1f1f1;
      width: 42px;
      text-align: center;
      line-height: 30px;
      font-size: 12px;
      color: #666;
    }
    .input-group {
      position: relative;
      display: flex;
      align-items: center;
      .label {
        font-size: 12px;
        color: #999;
        position: absolute;
        left: 20px;
        top: 35px;
      }
    }
    .title {
      margin-bottom: 5px;
      color: #888;
    }
    .print-setting {
      width: 600px;
      flex-shrink: 0;
    }
    .printer-w {
      margin-bottom: 20px;
    }
  }
  :deep(.arco-textarea) {
    font-size: 12px !important;
    height: 40px;
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
  .barcode-win {
    flex: 1;
    background-color: #f1f1f1;
    position: relative;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 515px;
    .link {
      position: absolute;
      right: 10px;
      top: 5px;
      color: #666;
    }
    .print-media-wapper {
      display: flex;
    }
    .print-media {
      background-color: #fff;
      overflow: hidden;
      font-family: '黑体';
      img {
        width: 100%;
        height: 100%;
      }
      .print-item {
        line-height: 1;
        position: absolute;
        top: 0;
        left: 0;
      }
    }
    .print-media-padding {
      position: relative;
      width: 100%;
      height: 100%;
    }
    .active {
      background-color: rgba(0, 110, 255, 0.1);
    }
  }
  .arco-radio {
    margin-right: 10px;
  }
</style>
